<template>
    <view class="container">
        <view class="inaver _30f2b4d">
            <view class="left _30f2b4d" @tap.stop.prevent="gohome">
                <image 
					class="icon _30f2b4d" 
					src="/static/img/home.png" 
					style="width: 50rpx; height: 50rpx; margin-top: 64rpx"
					/>
            </view>
        </view>
        <view style="text-align: center; padding-top: 320rpx">
            <image 
				src="/static/img/login_bg.jpg" 
				style="width: 400rpx; height: 400rpx; text-align: center" />
        </view>
        <view class="topbar-selectDate" :class="{'is_form':loginSwitchType == 1}">
            <!-- 登录提交 -->
            <view class="submit-layer">
                <!-- <view 
					class="weixin" 
					:style="'display: ' + 
					(loginSwitchType == 1 ? 
					'block' : 
					'none')"
					>
                    <view>
                        <u-button 
							shape="circle" 
							@click="loginSwitchType=3"
							>
							账号密码登入
						</u-button>
                    </view>
                </view> -->
				
				<view>
					<u-form :model="formData" :rules="rules" ref="form1">
						<u-form-item label="账号" prop="username">
							<u--input v-model="formData.username" placeholder="账号" />
						</u-form-item>
						<u-form-item label="密码" prop="password">
							<u-input
								v-model="formData.password"
								:type="isOpen?'text':'password'"
							>
								<template slot="suffix">
									<u-icon :name="isOpen?'eye-fill':'eye-off'" 
										@click="isOpen = !isOpen"></u-icon>
								</template>
							</u-input>
						</u-form-item>
						<u-button 
							shape="circle" 
							type="warning" 
							@click="submit" 
							customStyle="margin: 10px 0">
							登 录
						</u-button>
						<!-- <u-button shape="circle" @click="loginSwitchType = 1">返 回</u-button> -->
					</u-form>
				</view>
				</view>
            </view>
        </view>
    </view>
</template>
<script>
import { getPage } from '../../utils/config';
import { promisify, $empty, storage, $toast, http, Validate } from '../../utils/utils';
import wxApi from '../../utils/wxApi';
import api from '../../utils/api';
const app = getApp();
export default {
    data() {
        return {
            guid: '',
            scene: {},
            logged: 0,
			
			formData: {
				username: '',
				password: ''
			},
			rules: {
				username: {
					type: 'string',
					required: true,
					message: '用户名不能为空',
					trigger: ['blur', 'change']
				},
				password: [
					{
						type: 'string',
						required: true,
						message: '密码不能为空',
						trigger: ['blur', 'change']
					},
					{
						min: 6,
						max: 20,
						message: '密码在6-20个字符之间',
						trigger: ['blur', 'change']
					},
					{
						pattern: /^[^\u4e00-\u9fa5]*$/,
						message: '密码不能包含中文',
						trigger: ['change','blur'],
					}
				]
			},
			
			

            //判断是否登录 0未登录 1已登录
            pwIcon: 'eye-o',
            pwType: false,
            smsCode: '',
            checked: true,
            smsCodeBtn: false,
            smsCodeText: '获取验证码',
            loginSwitchType: 1,
            loginSwitchText: '账号密码登录',
            list: {},
            radio: 0,

            //userForm
            userForm: {
                userName: '',
                password: ''
            },

            //phoneForm
            phoneForm: {
                phoneNumber: '',
                smsCode: ''
            },

            localInfo: '',
            userId: '',
            userRank: '',
            bgurl: '',
            userNameError: '',
            passwordError: '',
            phoneNumberError: '',
            smsCodeError: '',
            smsCodeTimes: '',
            session_key: '',
            openid: '',
            modalstatus: false,
			isOpen:false,
        };
    }
    /**
     * 生命周期函数--监听页面加载
     */,
    onLoad(options) {
        const scene = decodeURIComponent(options.scene);
        // if (app.pid > 0) {
        //   //pid = app.pid;
        //   console.log(app.pid)
        // } else {
        //   app.pid = 10;

        // }
        if (options.scene) {
            const array = scene.split('=');
            if (array[0] == 'guid') {
				this.guid =  array[1]
            }
        }
        console.log(this.guid);
        /**
         * 页面参数
         */
        if (JSON.stringify(options) !== '{}') {
            if (options.guid) {
				this.guid =  options.guid
                console.log(options.guid);
            }
        }

        //判断是否登录
        app.globalData
            .getLogin()
            .then((res) => {
				this.logged = res;
				this.localInfo = res;
				this.userId = res.data.user.user_id;
				this.userRank = res.data.user.user_rank;
                console.log(this.userId);
                if (options.web) {
                    //网页自动登录
                    wxApi.navigateTo('/pages/web/web?id=https://m.zhiai888.com/badun/login/' + this.userId);
                } else if (res.data.user.user_id > 0) {
                    wxApi.navigateBack(1);
                }
            })
            .catch((res) => {
				this.logged = res
            });

    },

    /**
     * 右上角分享事件
     */
    onShareAppMessage(res) {},
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {
		// 如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则
		this.$refs.form1.setRules(this.rules)
	},
    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        uni.hideHomeButton();
        uni.hideShareMenu({
            success: (res) => {}
        });
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {},
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {},
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {},
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {},
    methods: {
		
		submitForm() {
			console.log('dayin:submitForm~~~~~~')
		      // 提交表单逻辑
		},

        /**
         * 密码切换显示
         */
        handleEye() {
			console.log('dayin:密码显示隐藏~~~~~')
            if (this.pwType) {
				this.pwIcon = 'eye-o';
				this.pwType = false
            } else {
				this.pwIcon = 'closed-eye';
				this.pwType = true
            }
        },



		
		// 手机号/短信码登录
		submit() {
			let that = this
			// 如果有错误，会在catch中返回报错信息数组，校验通过则在then中返回true
			this.$refs.form1.validate().then(res => {

				uni.showLoading({
					title: '登录中...',
					mask: true
				});
				http.post(api.default, {
				    data: {
				        action: 'login',
				        username: that.formData.username,
				        password: that.formData.password
				    }
				}).then(res=>{
					console.log('dayin:res~~~~~~~',res)
					const { data } = res.data;
					if (res.data.code == 0) {
					    //登录成功存储用户信息
					    app.globalData.setLogon(data, 1, () => {
					        //登录后跳转
					        $toast(`登录成功`, {
					            icon: 'success',
					            times: 1000
					        }).then(() => {
								http.get(
								    api.default,
								    {
								        data: {
								            action: 'district'
								        }
								    },
								    false
								).then((res) => {
								    const { data } = res.data;
									storage.set('regionInfo', data);
									this.getRegionInfo();
								});
					            if (data.bindwx == 1) {
					                wxApi.navigateTo(getPage.wx + '?uid=' + data.user.user_id);
					            } else {
					                wxApi.switchTab(getPage.home);
					            }
					            //wxApi.refreshPage();
					        });
					    });
					} else {
					    $toast(res.errmsg);
					}
				})
			}).catch(errors => {
				uni.$u.toast('请填写完整的信息')
			})
		},
		
		/**
		 * 获取地区
		 */
		getRegionInfo() {
		    http.get(
		        api.default,
		        {
		            data: {
		                action: 'district'
		            }
		        },
		        false
		    ).then((res) => {
		        const { data } = res.data;
		    	storage.set('regionInfo', data);
		        console.log('storage--城市数据------------data',data)
		    });
		},

        gohome() {
            wxApi.switchTab(getPage.home);
        }
    }
};
</script>
<style lang="scss">
@import './login.css';
</style>
